from flask_restful import Resource

from restful.api__.public__.info.atomic.UserAllFollowing import UserAllFollowing
from restful.model.PostsPaginationQuery import PostsPaginationQuery
from restful.api__.public__.info.composite.post.list._PostsList import  _PostsList
from restful.api__.session import login_required_current_user_generate, params_required
from restful.model.query import QueryMultipleInstances, QueryOneInstance
from restful.model.tables import Check, Blog
from restful.response import ResponseSuccess

class PostsListByMyFollowing(Resource):
    @login_required_current_user_generate
    @params_required({'limit': 'int','desc': 'bool','offset': 'int'})
    def get(self, current_user, limit,desc,offset):
        following = UserAllFollowing().get(uid=current_user.id)[0]['data']

        #TODO
        # pids=[]
        # for i in following:
        #     checks = QueryMultipleInstances(Check, {'checked': True, 'passed': True,'uid':i['uid']})
        #     for j in checks:
        #         pids.append(j.pid)

        pids=[1,2,3,4,5,6,7,8,9,10,11,12,13]

        data_=PostsPaginationQuery(data={
            'pids': pids,
            'limit': limit,
            'desc':desc,
            'offset':offset
        })

        posts_data={}
        posts_data['blogs']= _PostsList(data_['blogs'])
        posts_data.update({'offset':data_['offset']})
        return ResponseSuccess(data=posts_data)

class PostsListByMyFollowing_(Resource):
    @login_required_current_user_generate
    def get(self, current_user):
        following = UserAllFollowing().get(uid=current_user.id)[0]['data']

        posts=[]
        for i in following:
            checks = QueryMultipleInstances(Check, {'checked': True, 'passed': True,'uid':i['uid']})
            for j in checks:
                post = QueryOneInstance(Blog, {'id': j.pid})
                if post:
                    posts.append(post)


        posts_data = _PostsList(posts)
        sorted_posts = sorted(posts_data, key=lambda x: x['time'], reverse=True)
        return ResponseSuccess(data=sorted_posts)
